#include <stdio.h>
#include <config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <input_manager.h>
#include <tslib.h>

static struct tsdev *ts = NULL;
static struct ts_sample samp;
static int touchDevInit(void);
static int touchDevExit(void);
static int touchGetInputEvent(PT_inputEvent g_ptInputEvent);

static T_inputOpr touchInputOpr = 
{
	.name 				= "touch",
	.inputDeviceInit 	= touchDevInit,
	.inputDeviceExit 	= touchDevExit,
	.getInputEvent 		= touchGetInputEvent,
	.next				= NULL,
};

static int touchDevInit(void)
{
	ts = ts_setup(NULL, 0);
	if (ts == NULL) 
	{
		fprintf(stderr, "ts_setup error\n");
		return -1;
	}

	return 0;
}

static int touchDevExit(void)
{
	return 0;
}

static int touchGetInputEvent(PT_inputEvent g_ptInputEvent)
{
	if (ts_read(ts, &samp, 1) <0) 
	{
		fprintf(stderr, "ts_read error\n");
		return -1;
	}
	else
	{
		gettimeofday(&g_ptInputEvent->time,NULL);
		g_ptInputEvent->type = INPUT_TYPE_TOUCH;
		g_ptInputEvent->value = -1;
		g_ptInputEvent->x = (samp.x*LCDWIDTH)/4096;
		g_ptInputEvent->y = (samp.y*LCDHEIGHT)/4096;
		
		if(samp.pressure > 0)
		{
			g_ptInputEvent->pressed =1;
		}
		else if(samp.pressure == 0)
		{
			g_ptInputEvent->pressed =0;
		}
	}
	
	return 0;
}

int touchInit(void)
{
	int ret;

	ret = registerInputOpr(&touchInputOpr);
	return ret;

}

